package com.dnzx.controller.web;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.dnzx.framework.result.ResultUtils;
import org.dnzx.framework.result.domain.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.dnzx.auth.AuthenticatService;
import com.dnzx.model.MemberBO;
import com.dnzx.model.SmsBO;
import com.dnzx.model.system.RoleBO;
import com.dnzx.model.system.UserBO;
import com.dnzx.service.IMemberService;
import com.dnzx.service.IParamService;
import com.dnzx.service.IRoleService;
import com.dnzx.service.ISmsService;
import com.dnzx.service.IUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @author 
 * @version V1.0
 * @date
 */
@RestController
@RequestMapping("/web/auth")
@Api(value = "/web/auth", description = "认证接口", produces = MediaType.APPLICATION_JSON_VALUE)
public class WebAuthController {

    private static final Logger logger = LoggerFactory.getLogger(WebAuthController.class);

    @Autowired
    private ISmsService smsService;
    @Autowired
    private AuthenticatService authenticatService;
    @Autowired
	private IUserService userService;
    @Autowired
	private IRoleService roleService;
    @Autowired
	private IMemberService memberService;
    @Autowired
    private IParamService paramService;
    
    /**
	 * 注册
	 * @param memberBO
	 * @return
	 */
	@PostMapping(value = "/register")
    @ApiOperation(value = "/register",notes = "注册：shareId",httpMethod = "POST",produces = MediaType.APPLICATION_JSON_VALUE)
    public Result register(@ApiParam(value = "实体") @RequestBody @Valid MemberBO memberBO, HttpServletRequest request) {
		try {
			String langCode = request.getHeader("langCode");
			this.memberService.save(memberBO, langCode);
			
			String token = authenticatService.login(memberBO.getEmail(), memberBO.getPassword());
	    	UserBO userBOQuery = new UserBO();
	    	userBOQuery.setMobile(memberBO.getEmail());
	    	UserBO userBO = this.userService.get(userBOQuery);
	        userBO.setToken(token);
			
	        return ResultUtils.returnSuccess("SUCCESS", userBO);
        } catch (Exception e) {
            return ResultUtils.returnError(e.getMessage());
        }
    }

    /**
     * 
     * 用户登录
     */
    @PostMapping(value = "/login")
    @ApiOperation(value = "/login", notes = "用户登录(email和password)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result login(@RequestBody UserBO userBO, HttpServletRequest request) {
    	String langCode = request.getHeader("langCode");
        try {
        	// 查找用户信息，判断是否后台用户
        	userBO.setMobile(userBO.getEmail());
        	UserBO userBODb = this.userService.get(userBO);
    		String message = this.paramService.get("UNKNOWN_USER_" + langCode);// 该用户不存在
        	if (userBODb == null) {
        		throw new Exception(message);
        	}
        	// 查找用户信息，判断是否后台用户
        	RoleBO roleBO = this.roleService.get(userBODb.getRoleId());
        	if (roleBO == null || !"0".equals(roleBO.getIsAdmin())) {// 不是前台用户
        		throw new Exception(message);// 该用户不存在
        	}
        	String token = authenticatService.login(userBO.getMobile(), userBO.getPassword());
            userBO = this.userService.get(userBO);
            userBO.setToken(token);
            return ResultUtils.returnSuccess("SUCCESS", userBO);
        } catch (Exception e) {
        	if ("账户或密码错误".equals(e.getMessage()) && "en".equals(langCode)) {
        		return ResultUtils.returnError("Wrong account or password.");
        	} else {
        		return ResultUtils.returnError(e.getMessage());
        	}
        }

    }
    
    /**
     * 
     * 发送短信验证码
     */
    @PostMapping(value = "/sendSms")
    @ApiOperation(value = "/sendSms", notes = "发送注册的邮件验证码", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result sendSms(@RequestBody UserBO userBO, HttpServletRequest request) {
        try {
        	String mobile = userBO.getEmail();
        	// 查找用户信息，判断是否后台用户
        	userBO.setMobile(mobile);
        	UserBO userBODb = this.userService.get(userBO);
        	// 查找用户信息，判断是否后台用户
        	if (userBODb != null) {
        		RoleBO roleBO = this.roleService.get(userBODb.getRoleId());
            	if (roleBO != null && "0".equals(roleBO.getIsAdmin())) {// 不是前台用户
            		String langCode = request.getHeader("langCode");
            		String message = this.paramService.get("KNOWN_USER_" + langCode);// 该用户已存在
            		throw new Exception(message);
            	}
        	}
        	SmsBO smsBO = new SmsBO();
        	smsBO.setMobile(mobile);
        	Random random = new Random();
            int code = random.nextInt(99999) + 100000;
            int minutes = 2;
            
            String langCode = request.getHeader("langCode");
    		String validateCode = this.paramService.get("VALIDATE_CODE_" + langCode);// 验证码
    		String yourValidateCode = this.paramService.get("YOUR_VALIDATE_CODE_" + langCode);// 您的验证码为：
    		String validTime = this.paramService.get("VALID_TIME_" + langCode);// ，有效时间
    		String minuteStr = this.paramService.get("MINUTE_" + langCode);// 分钟。
            
        	String templateCode = "[YSLocker]" + validateCode;
        	String templateParam = "[YSLocker]" + yourValidateCode + code + validTime + minutes + minuteStr;
        	smsBO.setUserId(userBO.getId());
        	smsBO.setCode(String.valueOf(code));
        	smsBO.setTemplateCode(templateCode);
        	smsBO.setTemplateParam(templateParam);
        	smsBO.setContent(templateParam);
        	this.smsService.save(smsBO);
            return ResultUtils.returnSuccess("SUCCESS");
        } catch (Exception e) {
            return ResultUtils.returnError(e.getMessage());
        }
    }
    
    /**
     * 
     * 发送短信验证码
     */
    @PostMapping(value = "/sendForgetSms")
    @ApiOperation(value = "/sendForgetSms", notes = "发送忘记密码的邮件验证码", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result sendForgetSms(@RequestBody UserBO userBO, HttpServletRequest request) {
        try {
        	String mobile = userBO.getEmail();
        	UserBO userBOQuery = new UserBO();
        	userBOQuery.setMobile(mobile);
        	userBOQuery = this.userService.get(userBOQuery);
        	if (userBOQuery == null ) {
        		String langCode = request.getHeader("langCode");
        		String message = this.paramService.get("UNKNOWN_USER_" + langCode);// 该用户不存在
        		throw new Exception(message);
        	}
        	SmsBO smsBO = new SmsBO();
        	smsBO.setMobile(mobile);
        	Random random = new Random();
            int code = random.nextInt(99999) + 100000;
            int minutes = 2;
            
            String langCode = request.getHeader("langCode");
    		String validateCode = this.paramService.get("VALIDATE_CODE_" + langCode);// 验证码
    		String yourValidateCode = this.paramService.get("YOUR_VALIDATE_CODE_" + langCode);// 您的验证码为：
    		String validTime = this.paramService.get("VALID_TIME_" + langCode);// ，有效时间
    		String minuteStr = this.paramService.get("MINUTE_" + langCode);// 分钟。
            
    		String templateCode = "[YSLocker]" + validateCode;
        	String templateParam = "[YSLocker]" + yourValidateCode + code + validTime + minutes + minuteStr;
        	smsBO.setUserId(userBOQuery.getId());
        	smsBO.setCode(String.valueOf(code));
        	smsBO.setTemplateCode(templateCode);
        	smsBO.setTemplateParam(templateParam);
        	smsBO.setContent(templateParam);
        	this.smsService.save(smsBO);
            return ResultUtils.returnSuccess("SUCCESS");
        } catch (Exception e) {
            return ResultUtils.returnError(e.getMessage());
        }
    }
    
    /**
     * 
     * 发送短信验证码
     */
    @PostMapping(value = "/sendLoginSms")
    @ApiOperation(value = "/sendLoginSms", notes = "发送登录的邮件验证码", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result sendLoginSms(@RequestBody UserBO userBO, HttpServletRequest request) {
        try {
        	String mobile = userBO.getEmail();
        	UserBO userBOQuery = new UserBO();
        	userBOQuery.setMobile(mobile);
        	userBOQuery = this.userService.get(userBOQuery);
        	if (userBOQuery == null ) {
        		String langCode = request.getHeader("langCode");
        		String message = this.paramService.get("UNKNOWN_USER_" + langCode);// 该用户不存在
        		throw new Exception(message);
        	}
        	SmsBO smsBO = new SmsBO();
        	smsBO.setMobile(mobile);
        	Random random = new Random();
            int code = random.nextInt(99999) + 100000;
            int minutes = 2;
            String langCode = request.getHeader("langCode");
    		String validateCode = this.paramService.get("VALIDATE_CODE_" + langCode);// 验证码
    		String yourValidateCode = this.paramService.get("YOUR_VALIDATE_CODE_" + langCode);// 您的验证码为：
    		String validTime = this.paramService.get("VALID_TIME_" + langCode);// ，有效时间
    		String minuteStr = this.paramService.get("MINUTE_" + langCode);// 分钟。
            
    		String templateCode = "[YSLocker]" + validateCode;
        	String templateParam = "[YSLocker]" + yourValidateCode + code + validTime + minutes + minuteStr;
        	smsBO.setUserId(userBOQuery.getId());
        	smsBO.setCode(String.valueOf(code));
        	smsBO.setTemplateCode(templateCode);
        	smsBO.setTemplateParam(templateParam);
        	smsBO.setContent(templateParam);
        	this.smsService.save(smsBO);
            return ResultUtils.returnSuccess("SUCCESS");
        } catch (Exception e) {
            return ResultUtils.returnError(e.getMessage());
        }
    }
    
    /**
     * 修改密码（忘记密码中的确认按钮）
     * @param user
     * @param request
     * @return
     */
    @PostMapping(value = "/forgetPwd")
    @ApiOperation(value = "/forgetPwd", notes = "修改密码：email、code、password，不需要传确认密码", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result forgetPwd(@RequestBody UserBO userBO, HttpServletRequest request) {
        try {
            this.userService.forgetPwd(userBO);
            return ResultUtils.returnSuccess("SUCCESS");
        } catch (Exception e) {
        	e.printStackTrace();
            return ResultUtils.returnError(e.getMessage());
        }
    }
   
}	

